<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "project_single".
 *
 * @property int $id
 * @property int $level 评级
 * @property string $title 项目名称
 * @property int $province 省份
 * @property int $city 城市
 * @property int $category 分类
 * @property string $tag 标签
 * @property string $creditor 项目持有方
 * @property string $detail 项目情况
 * @property string $asset 涉及资产情况
 * @property string $address 地址
 * @property string $area 面积
 * @property string $price 项目卖价
 * @property string $price_per_area 市场单价
 * @property string $price_pre_evaluate 预估市场价值
 * @property string $evaluate_by 评估依据
 * @property string $highlights 亮点介绍
 * @property string $contact 联系人情况及联系方式
 * @property string $history 沟通情况
 * @property string $follow 跟进方向
 * @property string $source 网址链接
 * @property int $owner 上传人
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 */
class ProjectSingle extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_single';
    }

    public function attributes()
    {
        return array_merge(parent::attributes(), ['tagTitle']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['level', 'title', 'province', 'city', 'category',], 'required'],
            [['level', 'province', 'city', 'category', 'owner'], 'integer'],
            [['area', 'price', 'price_per_area', 'price_pre_evaluate'], 'number'],
            [['area', 'price', 'price_per_area', 'price_pre_evaluate','is_published'], 'default', 'value' => 0],
            [['creditor', 'detail', 'asset', 'address', 'evaluate_by', 'highlights', 'contact', 'history', 'follow', 'source',], 'default', 'value' => ''],
            [['detail', 'asset', 'evaluate_by', 'highlights', 'history', 'follow', 'source', 'tagTitle', 'created_at', 'updated_at', 'tag', 'contact', 'title', 'creditor', 'address'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'level' => '评级',
            'title' => '项目名称',
            'province' => '省份',
            'city' => '城市',
            'category' => '分类',
            'tag' => '标签',
            'creditor' => '项目持有方',
            'detail' => '项目情况',
            'asset' => '涉及资产情况',
            'address' => '地址',
            'area' => '面积（平米）',
            'price' => '项目卖价（元）',
            'price_per_area' => '市场单价（元）',
            'price_pre_evaluate' => '预估市场价值（元）',
            'evaluate_by' => '评估依据',
            'highlights' => '亮点介绍',
            'contact' => '联系人情况及联系方式',
            'history' => '沟通情况',
            'follow' => '跟进方向',
            'source' => '网址链接',
            'owner' => '上传人',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * @inheritdoc
     * @return ProjectSingleQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new ProjectSingleQuery(get_called_class());
    }

    public function getPublisher()
    {
        return $this->hasOne(User::className(), ['id' => 'owner']);
    }

    public function processData($filename)
    {
        $imported_data = \moonland\phpexcel\Excel::import(
            $filename,
            [
                'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
                'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
                'getOnlySheet' => 'Sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
            ]);

        //清单入库
        if (is_array($imported_data) && count($imported_data) > 0) {
            $model = new ProjectSingle();
            $project_fields = $this->attributeLabels();
            $success_count = 0;
            $failed_count = 0;
            $errors = [];
            $modelTag = new Tags();
            foreach ($imported_data as $key => $item) {
                //借款人为空则执行下一个循环
                if (empty($item[$this->getAttributeLabel('title')])) {
                    continue;
                }
                $cloneModel = clone $model;
                foreach ($project_fields as $field_name => $label) {
                    switch ($field_name) {
                        case 'title':
                            //已导入的不再导入
                            if (ProjectSingle::find()->where(['title' => $item[$this->getAttributeLabel('title')], 'owner' => Yii::$app->user->id])->one()) {
                                $errors ['exist'][] = $item[$this->getAttributeLabel('title')];
                                continue 3;
                            }
                            $cloneModel->title = $item[$label];
                            break;
                        case 'level':
                            $project_single_level = array_flip(Yii::$app->params['project_single_level']);
                            $cloneModel->level = $project_single_level[$item[$label]];
                            break;
                        case 'province':
                            $province = Country::findOne(['title' => $item[$label]])->id;
                            $cloneModel->province = $province ? $province : 0;
                            break;
                        case 'city':
                            $city = Country::find()->where("`title` = '" . $item[$label] . "' AND `pid` > 0")->one()->id;
                            $cloneModel->city = $city ? $city : 0;
                            break;
                        case 'category':
                            $project_category = array_flip(Yii::$app->params['project_single_category']);
                            $category = $project_category[$item[$label]];
                            $cloneModel->category = $category ? $category : 0;
                            break;
                        case 'tag':
                            $tags = [];
                            $labels = explode('，', $item[$label]);
                            if (count($labels) > 0) {
                                foreach ($labels as $label_item) {
                                    if ($tag_id = Tags::find()->where("`title`='" . $label_item . "' AND (`user_id`=0 OR `user_id`=" . Yii::$app->user->id . ")")->one()->id) {
                                        $tags[] = $tag_id;
                                    } else {
                                        $modelTagClone = clone $modelTag;
                                        $modelTagClone->title = $label_item;
                                        $modelTagClone->user_id = Yii::$app->user->id;
                                        if ($modelTagClone->save()) {
                                            $tags[] = $modelTagClone->id;
                                        }
                                    }
                                }
                                $cloneModel->tag = implode(',', $tags);
                            }
                            break;
                        default:
                            $cloneModel->$field_name = $item[$label];
                    }
                }
                $cloneModel->created_at = date('Y-m-d H:i:s');
                $cloneModel->updated_at = date('Y-m-d H:i:s');
                $cloneModel->owner = Yii::$app->user->id;
                if ($cloneModel->save()) {
                    $success_count++;
                } else {
                    $failed_count++;
                    if (count($cloneModel->getFirstErrors()) > 0) {
                        echo json_encode(['error' => $item[$this->getAttributeLabel('title')] . '未导入' . serialize($cloneModel->getFirstErrors())]);
                        return;
                    }
                }
            }

            $msg = '';
            if (count($errors['exist']) > 0) {
                $msg .= '以下项目已经导入过了：<hr>' . implode('、', $errors['exist']) . '<hr>';
            }
            if ($success_count == 0) {
                $msg2 = '请检查导入的文件格式是否符合模板要求。';
            }
            echo json_encode(['error' => $msg . '成功导入' . $success_count . '条。失败' . $failed_count . '条。' . $msg2]);
            return;

        } else {
            echo json_encode(['error' => '表中无数据']);
            return;
        }

    }

}
